package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.RequestParams;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderLogisticsService;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.UserHolder;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private UserClient userClient;
    @Autowired
    private IOrderLogisticsService orderLogisticsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Transactional
    @Override
    public Long createOrder(RequestParams params) {

        Order order = new Order();
        Item item = itemClient.queryItemById(params.getItemId());

        long totalFee = item.getPrice() * params.getNum();
        order.setTotalFee(totalFee);
        order.setPaymentType(params.getPaymentType());
        order.setUserId(UserHolder.getUser());
        order.setStatus(Order.OrderStatus.UNPAY.getState());
        this.save(order);

        OrderDetail detail = new OrderDetail();
        detail.setTitle(item.getName());
        detail.setSpec(item.getSpec());
        detail.setPrice(item.getPrice());
        detail.setNum(params.getNum());
        detail.setItemId(item.getId());
        detail.setImage(item.getImage());
        detail.setOrderId(order.getId());
        orderDetailService.save(detail);

        Address address = userClient.findAddressById(params.getAddressId());
        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(address, orderLogistics);
        orderLogistics.setOrderId(order.getId());
        orderLogisticsService.save(orderLogistics);

        try {
            itemClient.updateStock(item.getId(), params.getNum());
        } catch (Exception e) {
            throw new RuntimeException("库存不足!");
        }

        String exchangeName = "delay.direct";
        String routingKey = "delay";
        String msg = order.getId().toString();
        Long delayTimeMills = 30L * 60 * 1000;
        Message message = MessageBuilder.withBody(msg.getBytes(StandardCharsets.UTF_8)).setHeader("x-delay", delayTimeMills).build();
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(exchangeName, routingKey, message, correlationData);
        return order.getId();
    }

    @Override
    public void cancelOrder(Long orderId) {
        Order order = getById(orderId);
        if (!order.getStatus().equals(Order.OrderStatus.UNPAY.getState())) {
            return;
        }
        order.setStatus(Order.OrderStatus.CANCEL.getState());
        updateById(order);
        List<OrderDetail> orderDetailList = orderDetailService.query().eq("order_id", orderId).list();
        for (OrderDetail detail : orderDetailList) {
            Integer num = detail.getNum();
            itemClient.updateStock(detail.getItemId(), num * -1);
        }
    }
}
